package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.byit.domain.SysUser;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.ISysRoleMeunService;
import com.byit.service.ISysRoleService;
import com.byit.shrio.session.SessionAttr;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.PasswordUtil;
import com.byit.utils.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/login")
public class SysLoginController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysRoleMeunService sysRoleMeunService;

    @Autowired
    private ISysRoleService roleService;

    @RequestMapping("")
    @Log(title = "用户登录", operate = OperatorType.USER_LOGIN, channel = ChannelType.WEB_INTER)
    public Object ajaxLogin(@RequestParam String username, @RequestParam String password, HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, PasswordUtil.pwdEncryptOne(password));
        Subject subject = SecurityUtils.getSubject();
        try {
            JSONObject jsonObject = new JSONObject();
            subject.login(token);
            jsonObject.put("token", subject.getSession().getId());
            SysUser user = (SysUser) subject.getPrincipal();
            session.setAttribute(SessionAttr.userInfo, user);
            session.setAttribute(SessionAttr.userId, user.getId());
            session.setAttribute(SessionAttr.loginName, user.getLoginName());
            session.setAttribute(SessionAttr.userName, user.getRealName());
            session.setAttribute(SessionAttr.userDeptId, user.getDeptId());
            session.setAttribute(SessionAttr.companyId, user.getCompanyId());
            return MessageResult.warpper(PromptInfo.SYS_SECCUSS.getCode(), jsonObject, "登录成功");
        } catch (IncorrectCredentialsException e) {
            return MessageResult.warpper(PromptInfo.USER_ACCOUNT_PASS_ERROR, e.getMessage());
        } catch (LockedAccountException e) {
            return MessageResult.warpper(PromptInfo.ERROR_ACCOUNT_FROZZEN, e.getMessage());
        } catch (AuthenticationException e) {
            return MessageResult.warpper(PromptInfo.ACCOUNT_NOT_EXISTS, e.getMessage());
        } catch (Exception e) {
            return MessageResult.warpper(PromptInfo.SERVER_BUSY, e.getMessage());
        }
    }

    /**
     * 获取登录用户权限信息
     */
    @GetMapping("/userInfo")
    public Object userInfo(HttpSession session) {
        SysUser user = SessionHelper.getUser(session);
        if (null == user) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        List<String> authUserRole = roleService.getAuthUserRole(user.getId());
        Map<String, Object> map = new HashedMap();
        map.put("roles", authUserRole);

        map.put("avatar", (null == user.getIcon()) ? "" : user.getIcon());
        map.put("name", user.getLoginName());
        List<JSONObject> list = sysRoleMeunService.getMenuRoleList(user.getId());
        JSONObject json = new JSONObject();
        for (JSONObject obj : list) {
            json.put(obj.getString("perms"), StringUtil.splitStr(obj.getString("roleCode"), ","));
        }
        map.put("asyncRouterMap", json);
        map.put("userType", user.getUserType());
        map.put("isManager", user.getIsManager());
        return MessageResult.success(map);
    }

    /**
     * 用户退出
     */
    @RequestMapping("/out")
    public Object loginout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return MessageResult.success();

    }
}